package com.xframe.xdal.core.handler;

import com.xframe.xdal.core.domain.XDynamicModel;
import com.xframe.xdal.core.util.StringUtil;
import com.xframe.xdal.core.util.XReflect;
import lombok.extern.log4j.Log4j2;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

@Log4j2
public class XDynamicModelListHandler implements ResultSetHandler<List<XDynamicModel>>{



    @Override
    public List<XDynamicModel> handle(ResultSet resultSet) {
        try {
            if (resultSet == null) {
                return null;
            }
            ResultSetMetaData meta = resultSet.getMetaData();

            List<XDynamicModel> list = new ArrayList<>();
            int columnCount = meta.getColumnCount();
            while (resultSet.next()) {
                XDynamicModel xDynamicModel = new XDynamicModel();
                for (int colIndex = 1; colIndex < columnCount + 1; colIndex++) {


                    Object val = resultSet.getObject(colIndex);
                    String catalogName = meta.getCatalogName(colIndex);
                    String className = meta.getColumnClassName(colIndex);
                    String colName = meta.getColumnName(colIndex);
                    String label = meta.getColumnLabel(colIndex);
                    int colType = meta.getColumnType(colIndex);
                    String schemaName = meta.getSchemaName(colIndex);
                    XReflect.setFieldValue(xDynamicModel, StringUtil.underScoreCaseTocCamel(colName),resultSet,colIndex);

                }
                list.add(xDynamicModel);
            }
            return list;
        }catch (Exception exception) {
            exception.printStackTrace();
            //log.error("exception={}",exception);
            return null;
        }
    }
}
